<template>
  <div>
    <el-card>
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane :label="firstLabel" name="first"></el-tab-pane>
        <el-tab-pane :label="secondLabel" name="second"></el-tab-pane>
        <el-tab-pane :label="thirdLabel" name="third"></el-tab-pane>
        <el-tab-pane :label="fourthLabel" name="fourth"></el-tab-pane>
        <el-tab-pane :label="fiveLabel" name="five"></el-tab-pane>
      </el-tabs>

      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="formInline.goodsName" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-tree-select
            v-model="formInline.categoryId"
            :data="treeData"
            :props="treeProps"
            :render-after-expand="false"
            style="width: 240px"
            placeholder="请选择商品分类"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onQuery">查询</el-button>
          <el-button type="warning" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="btn-list">
        <el-button @click="addGoods">新增商品</el-button>
      </div>

      <el-table :data="tableData" style="width: 100%" border stripe>
        <el-table-column type="expand" width="55">
          <template #default="props">
            <el-row style="margin-left: 50px;">
              <el-col :span="8"><span>商品分类：{{ props.row.categoryName }}</span></el-col>
              <el-col :span="8"><span>市场价：{{ props.row.originalPrice }}</span></el-col>
              <el-col :span="8"><span>成本价：{{ props.row.costPrice }}</span></el-col>
            </el-row>
            <el-row style="margin-left: 50px;">
              <el-col :span="8"><span>收藏：{{ props.row.collect }}</span></el-col>
              <el-col :span="8"><span>虚拟销量：{{ props.row.virtualSalesVolume }}</span></el-col>
              <el-col :span="8"></el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column property="goodsCoverUrl" label="商品图" width="150" align="center">
          <template #default="scope">
            <el-image 
                style="width: 100px;height: 100px;"
                :src="scope.row.goodsCoverUrl" 
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="[scope.row.goodsCoverUrl]"
                preview-teleported
                fit="cover"/>
          </template>
        </el-table-column>
        <el-table-column property="goodsName" label="商品名称" show-overflow-tooltip width="120" align="center"/>
        <el-table-column property="salePrice" label="商品售价" width="100" align="center" show-overflow-tooltip/>
        <el-table-column property="salesVolume" label="销量" width="80" align="center" show-overflow-tooltip/>
        <el-table-column property="totalStock" label="库存" width="80" align="center" show-overflow-tooltip />
        <el-table-column property="sort" label="排序" width="80" show-overflow-tooltip />
        <el-table-column property="createTime" label="添加时间" show-overflow-tooltip width="150" align="center"/>
        <el-table-column property="status" label="状态" width="80" align="center" show-overflow-tooltip>
          <template #default="scope">
            {{ statusData.filter(item => item.id === scope.row.status)[0].name }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button size="small" v-if="formInline.type !== 4" @click="handleEdit(scope.row)" link>
              修改
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              v-if="formInline.type !== 4"
              link
            >
              删除
            </el-button>
            <el-button v-if="scope.row.status === 1 && formInline.type !== 4" type="primary" link size="small" @click="handleIn(scope.row)">上架</el-button>
            <el-button v-if="scope.row.status === 0 && formInline.type !== 4" type="primary" link size="small" @click="handleOut(scope.row)">下架</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[20, 50, 100, 200]"
        size="default"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

    </el-card>
  </div>
</template>

<script setup>
  import { ref, reactive } from 'vue'
  import { useRouter } from 'vue-router'
  import { tableList, getCategory, queryTypeNum, removeGoods, inOrOut } from '~/api/product/goods'
  import { ElMessageBox } from 'element-plus'
  import { showMessage } from '~/utils/my-notification'

  // 使用 useRouter 创建一个 router 实例
  const router = useRouter()

  const activeName = ref('first') // el-tabs初始化时选择第一个
  const currentPage = ref(1) // 当前页数
  const pageSize = ref(20) // 每页多少条数据
  const background = ref(false) // 是否为分页按钮添加背景色
  const disabled = ref(false) // 是否禁用分页
  const total = ref(0) // 总条目数
  const tableData = ref([]) // 表格数据
  const treeData = ref([]) // 商品分类el-tree-select的数据
  const treeProps = { label: 'categoryName', children: 'children', value: 'id' }
  const firstLabel = ref('出售中的商品(0)')
  const secondLabel = ref('仓库中的商品(0)')
  const thirdLabel = ref('已经售罄商品(0)')
  const fourthLabel = ref('警戒库存(0)')
  const fiveLabel = ref('商品回收站(0)')

  const statusData = [
    { id: 0, name: '上架' },
    { id: 1, name: '下架' }
  ]

  const formInline = reactive({
    goodsName: '',
    categoryId: '',
    type: 0,
    page: currentPage.value,
    limit: pageSize.value
  })

  // 表格数据查询
  onQuery()
  // 商品分类数据查询
  onQueryCategory()
  // 查询各个分类的总计
  onQueryTypeNum()
  // 商品分类数据查询
  function onQueryCategory() {
    getCategory().then(res => {
      if(res && res.data.code === 200) {
        treeData.value = res.data.data
      }
    })
  }
  // 查询表格数据
  function onQuery() {
    tableList(formInline).then(res => {
      if(res && res.data.code === 200) {
        const datas = res.data.data.records
        tableData.value = datas
        total.value = res.data.data.total
      }
    })
  }
  // 查询各个分类的总计
  function onQueryTypeNum() {
    queryTypeNum().then(res => {
      if(res && res.data.code === 200) {
        const data = res.data.data
        firstLabel.value = '出售中的商品(' + data.first + ')'
        secondLabel.value = '仓库中的商品(' + data.second + ')'
        thirdLabel.value = '已经售罄商品(' + data.third + ')'
        fourthLabel.value = '警戒库存(' + data.fourth + ')'
        fiveLabel.value = '商品回收站(' + data.five + ')'
      }
    })
  }
  // 重置
  function onReset() {}
  // tabs点击事件
  function handleClick(tab, event) {
    const name = tab.props.name
    if(name === 'first') {
      formInline.type = 0
    } else if(name === 'second') {
      formInline.type = 1
    } else if(name === 'third') {
      formInline.type = 2
    } else if(name === 'fourth') {
      formInline.type = 3
    } else {
      formInline.type = 4
    }
    onQuery()
  }
  // 新增商品
  function addGoods() {
    router.push({ path: './goods-add-or-update'})
  }
  // 修改
  function handleEdit(row) {
    // console.log('row', row)
    router.push({ path: 'goods-add-or-update', query: {id: row.id}})
  }
  // 删除
  function handleDelete(row) {
    ElMessageBox.confirm(`确定进行删除操作?`, '提示',{
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false
    }).then(() => {
      removeGoods(row.id).then(res => {
        if(res && res.data.code === 200) {
          onQuery()
          onQueryTypeNum()
          showMessage('删除成功!')
        }
      })
    }).catch(() => {

    })
  }
  // 上架
  function handleIn(row) {
    const id = row.id
    ElMessageBox.confirm(`确定将ID为[${id}]进行上架操作?`, '提示',{
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false
    }).then(() => {
      goodsInOrOut(id, 0)
    }).catch((err) => {
      console.log('kjsldjfaldjklsjf', err)
    })
  }
  // 下架
  function handleOut(row) {
    const id = row.id
    ElMessageBox.confirm(`确定将ID为[${id}]进行下架操作?`, '提示',{
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false
    }).then(() => {
      goodsInOrOut(id, 1)
    }).catch(() => {

    })
  }
  function goodsInOrOut(id, type) {
    inOrOut(id, type).then(res => {
      if(res && res.data.code === 200) {
        const data = res.data.data
        if(data && type === 0) {
          showMessage('上架成功!')
          onQuery()
          onQueryTypeNum()
        } else if(data && type === 1) {
          showMessage('下架成功')
          onQuery()
          onQueryTypeNum()
        } else {
          showMessage('出错了，请联系管理员处理!', 'error')
        }
      }
    })
  }

  const handleSizeChange = (val) => {
    console.log(`${val} items per page`)
  }
  const handleCurrentChange = (val) => {
    currentPage.value = val
    onQuery()
  }
</script>
<style>
  .el-pagination {
    margin-top: 20px;
    margin-bottom: 20px;
    float: right;
  }

  .btn-list {
    margin-bottom: 20px;
  }

  .el-row {
    margin-bottom: 20px;
  }
  .el-row:last-child {
    margin-bottom: 0;
  }
  .el-col {
    border-radius: 4px;
  }

  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
</style>